package com.sjq.demo.exception;

import com.sjq.demo.response.BaseRespCode;
import com.sjq.demo.response.Result;
import org.pac4j.core.exception.http.UnauthorizedAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler extends BasicErrorController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public GlobalExceptionHandler() {
        super(new DefaultErrorAttributes(), new ErrorProperties());

    }

    public GlobalExceptionHandler(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    /**
     * 其他异常，系统繁忙，请稍候再试"
     */
    @ExceptionHandler(value = Exception.class)
    public <T> Result<Object> handleException(Exception e) {
        logger.error("其他异常！原因是:", e);
        return Result.error(BaseRespCode.SYSTEM_BUSY.getCode(), BaseRespCode.SYSTEM_BUSY.getMsg());
    }

    /**
     * 用户token验证失败异常
     *
     * @param e
     * @param <T>
     * @return
     */
    @ExceptionHandler(value = UnauthorizedAction.class)
    public <T> Result<Object> handleException(UnauthorizedAction e) {
        logger.error("用户验证异常！原因是:", e);
        return Result.error(BaseRespCode.LOGIN_FAILE.getCode(), BaseRespCode.LOGIN_FAILE.getMsg());
    }

    /**
     * 空指针异常
     * @param e
     * @param <T>
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public <T> Result<Object> handleException(NullPointerException e) {
        logger.error("空指针异常！原因是:", e);
        return Result.error(BaseRespCode.NULL.getCode(), BaseRespCode.NULL.getMsg());
    }


}
